package com.ruoyi.cloudsyncfile.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class OSSUtil {

    //设置oss端点
    private final String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    //设置OSS的keyid
    private final String accessKeyId = "LTAI5tCrniwSoc1hKQqTaK8T";
    //设置OSS的keysecr
    private final  String accessKeySecret = "nRkUDwAbJRKi2eS3e2t55bMjW8FFQI";
    //设置桶名
    private final String bucketName = "rz-cloudsync";

    //实例化oss客户端对象，通过该对象实现oss的各种业务操作
    //通过更改endpoint，accessKeyId，accessKeySecret来选择实例化哪个账号的客户端对象
    OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    /**
     * 传入用户上传的文件，并返回需要渲染的URL
     *
     * @param file
     * @return url
     * @throws IOException
     */
    public String upload(MultipartFile file) throws IOException {
        //获取文件流
        InputStream is = file.getInputStream();
        //对文件名字进行编辑，主要是防止文件被覆盖
        String filename = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss")) + file.getName();
        //将文件存入桶中
        ossClient.putObject(bucketName, filename, is);
        //根据文件名字配置URL
        String url = endpoint.split("//")[0] + "//" + bucketName + "." +
                endpoint.split("//")[1] + "/" + filename;
        //关闭客户端对象
        ossClient.shutdown();
        //然后将url返回
        return url;
    }
}